package cConsole

import (
	"fmt"

	"github.com/fatih/color"
)

type HelpConsole struct{}

func (i *HelpConsole) Desc() *ConsoleDesc {
	return &ConsoleDesc{
		Name: "help",
		Methods: []*ConsoleMethod{
			{
				Name:   "doc",
				Desc:   "查看帮助文档",
				Params: []*ConsoleParams{},
			},
		},
	}
}

func (i *HelpConsole) Doc() {
	type document struct {
		Name string
		Desc string
		Type uint8
	}
	var doc = []*document{}
	var maxlen int

	color.Set(color.FgHiCyan)
	fmt.Println(version)
	fmt.Println("")

	container.Range(func(instance any) {
		console := instance.(ConsoleInterface)
		desc := console.Desc()
		doc = append(doc, &document{
			Name: desc.Name,
			Desc: "",
			Type: 0,
		})
		maxlen = max(maxlen, len(desc.Name))
		for _, method := range desc.Methods {
			methodLabel := fmt.Sprintf("  %s::%s", desc.Name, method.Name)
			doc = append(doc, &document{
				Name: methodLabel,
				Desc: method.Desc,
				Type: 1,
			})
			maxlen = max(maxlen, len(methodLabel))
			for _, param := range method.Params {
				var paramLabel string
				if param.Optional {
					paramLabel = fmt.Sprintf("      [--%s]", param.Name)
				} else {
					paramLabel = fmt.Sprintf("      --%s", param.Name)
				}
				doc = append(doc, &document{
					Name: paramLabel,
					Desc: fmt.Sprintf("    %s", param.Desc),
					Type: 2,
				})
				maxlen = max(maxlen, len(paramLabel))
			}
		}
		doc = append(doc, &document{
			Name: "",
			Desc: "",
			Type: 1,
		})
	})

	// color.Set(color.FgGreen)
	// fmt.Printf("%s\n\n%s\n\n%s\n\n", "========================================", "eg: csingo command [--option=] ...", "========================================")
	for _, item := range doc {
		maxlenStr := fmt.Sprintf("%d", maxlen*-1)
		switch item.Type {
		case 0:
			color.Set(color.FgHiMagenta)
		case 1:
			color.Set(color.FgGreen)
		case 2:
			color.Set(color.FgHiBlue)
		}
		fmt.Printf("%"+maxlenStr+"s %s\n", item.Name, item.Desc)
	}
	color.Set(color.FgWhite)
}
